package com.guicent.geekai.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guicent.geekai.client.GeekAiClient;
import com.guicent.geekai.entity.ChatMessage;
import com.guicent.geekai.entity.ChatSession;
import com.guicent.geekai.entity.dto.GeekAiRequestDTO;
import com.guicent.geekai.entity.dto.MessageDTO;
import com.guicent.geekai.entity.dto.ThinkingDTO;
import com.guicent.geekai.mapper.ChatMessageMapper;
import com.guicent.geekai.mapper.ChatSessionMapper;
import com.guicent.geekai.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class ChatService {

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private GeekAiClient geekAiClient;

    @Value("${geekai.model}")
    private String model;

    // 创建新会话（保持不动）
    public ChatSession createSession(Long userId, String sessionTitle) {
        ChatSession session = new ChatSession();
        session.setUserId(userId);
        session.setSessionTitle(sessionTitle);
        session.setCreateTime(LocalDateTime.now());
        session.setUpdateTime(LocalDateTime.now());
        chatSessionMapper.insert(session);
        return session;
    }

    // 发送用户消息，并调用 GeekAI 接口
    public R sendMessage(Long sessionId, String userMessage) {
        // 保存用户消息
        ChatMessage userMsg = new ChatMessage();
        userMsg.setSessionId(sessionId);
        userMsg.setSender("user");
        userMsg.setContent(userMessage);
        userMsg.setCreateTime(LocalDateTime.now());
        chatMessageMapper.insert(userMsg);

        // 构建对话上下文消息（只获取历史消息，不添加 systemMsg）
        List<MessageDTO> messages = new ArrayList<>();
        List<ChatMessage> contextMessages = chatMessageMapper.selectBySessionId(sessionId);
        for (ChatMessage msg : contextMessages) {
            MessageDTO m = new MessageDTO();
            m.setRole(msg.getSender().equalsIgnoreCase("user") ? "user" : "assistant");
            m.setContent(msg.getContent());
            messages.add(m);
        }

        // 构造思考参数
        ThinkingDTO thinking = new ThinkingDTO();
        thinking.setType("enabled");
        thinking.setBudget_tokens(16000);
        thinking.setReasoning_effort("medium");

        // 构造 GeekAI 请求对象
        GeekAiRequestDTO request = new GeekAiRequestDTO();
        request.setModel(model);
        request.setMessages(messages);
        request.setThinking(thinking);
        request.setStream(false);
        request.setEnable_search(true);
        request.setRetries(3);
        request.setTemperature(1.3);
        request.setMax_completion_tokens(4096);
//        request.setJson_mode(true);
        request.setJson_mode(false);  // 关闭 json_mode
        request.setTool_choice("auto");
        request.setParallel_tool_calls(true);
        request.setStop(null);
        request.setLogprobs(false);
        request.setTop_logprobs(2);
        request.setFrequency_penalty(0);
        request.setPresence_penalty(0);
        request.setTop_p(1);
        request.setSeed(123);
        request.setN(1);
        request.setMetadata(new HashMap<>());

        // 调用 GeekAI 接口，返回 ResponseEntity<String>
        ResponseEntity<String> response = geekAiClient.chat(request);

        // 采用 provided 代码解析返回结果
        if (response.getStatusCode() == HttpStatus.OK) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(response.getBody());
                JsonNode choicesNode = jsonNode.get("choices");
                if (choicesNode != null && choicesNode.isArray() && choicesNode.size() > 0) {
                    JsonNode messageNode = choicesNode.get(0).get("message");
                    if (messageNode != null && messageNode.has("content")) {
                        String responseData = messageNode.get("content").asText();
                        System.out.println("AI 回复: " + responseData);

                        // 保存 AI 回复到数据库
                        ChatMessage aiMsg = new ChatMessage();
                        aiMsg.setSessionId(sessionId);
                        aiMsg.setSender("AI");
                        aiMsg.setContent(responseData);
                        aiMsg.setCreateTime(LocalDateTime.now());
                        chatMessageMapper.insert(aiMsg);
                        return R.ok().data("assistant",responseData);
                    }
                }
                return R.error().message("错误：AI 返回的数据格式异常");
            } catch (Exception e) {
                e.printStackTrace();
                return R.error().message("错误：解析 AI 返回数据失败");
            }
        } else {
            return R.error().message("错误：请求失败，状态码 " + response.getStatusCode());
        }
    }

    // 根据用户 ID 查询所有会话
    public List<ChatSession> getSessionsByUserId(Long userId) {
        QueryWrapper<ChatSession> query = new QueryWrapper<>();
        query.eq("user_id", userId);
        return chatSessionMapper.selectList(query);
    }

    // 查询会话中的详细消息
    public List<ChatMessage> getMessagesBySessionId(Long sessionId) {
        return chatMessageMapper.selectBySessionId(sessionId);
    }
}
